package com.gitee.wsl.io.channel.read.ext

import com.gitee.wsl.annotation.InternalAPI
import com.gitee.wsl.io.channel.CHANNEL_MAX_SIZE
import com.gitee.wsl.io.channel.read.ByteReadChannel
import com.gitee.wsl.io.channel.write.ByteWriteChannel
import com.gitee.wsl.io.discard
import com.gitee.wsl.io.remaining
import com.gitee.wsl.io.size
import kotlinx.io.InternalIoApi


@OptIn(InternalAPI::class, InternalIoApi::class)
val ByteReadChannel.availableForRead: Int
    get() = readBuffer.buffer.size.toInt()

@OptIn(InternalAPI::class)
suspend fun ByteReadChannel.discard(max: Long = Long.MAX_VALUE): Long {
    var remaining = max
    while (remaining > 0 && !isClosedForRead) {
        if (availableForRead == 0) {
            awaitContent()
        }
        val count = minOf(remaining, readBuffer.remaining)
        readBuffer.discard(count)

        remaining -= count
    }

    return max - remaining
}